package com.itheima.web.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.Question;
import com.itheima.domain.Result;
import com.itheima.factory.BeanFactory;
import com.itheima.service.QuestionService;
import com.itheima.utils.BeanUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 该Servlet处理说有的CRUD操作
 * 分页查询: http://localhost:8080/heima_mm/store/question/findByPage?currentPage=1&pageSize=5;
 * 新增:http://localhost:8080/heima_mm/store/question/save
 * 新增:http://localhost:8080/heima_mm/store/question/edit
 * 新增:http://localhost:8080/heima_mm/store/question/delete
 *
 */
@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {
       private QuestionService questionService = BeanFactory.getBean("questionService", QuestionService.class);


       private Result upload(HttpServletRequest request, HttpServletResponse response)throws IOException{
           try {
           //1. 创建DiskFileItemFactory磁盘工厂对象
           DiskFileItemFactory factory = new DiskFileItemFactory();
           //2. 创建ServletFileUpload文件上传核心对象
           ServletFileUpload fileUpload = new ServletFileUpload(factory);
           //3.解析请求,获取所有表单项FileItems,对于我们的项目而已,其实每次只会上传一张图片
               FileItem fileItem = fileUpload.parseRequest(request).get(0);
               //4.将图片写到服务器硬盘中
               //4.1 获取保存文件的目录
               String realPath = getServletContext().getRealPath("/upload");
               //4.2 获取文件名
               String filename = fileItem.getName();
               //需求:保证图片名唯一
               String uuid = UUID.randomUUID().toString().replace("-", "");
               //获取原文件的后缀名
               String suffix = filename.substring(filename.lastIndexOf("."));
               //4.3 将图片写在磁盘中
               filename =uuid+suffix;
               fileItem.write(new File(realPath,filename));
               return new Result(true,MessageConstant.UPLOAD_QUESTIONIMG_SUCCESS,filename);
           } catch (Exception e) {
               e.printStackTrace();
               return new Result(false,MessageConstant.UPLOAD_QUESTIONIMG_FAIL);
           }
       }
    private Result findAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            //调用service,根据id查询信息

            List<Question> list = questionService.findAll();
            //响应给过到客户端
            return new Result(true,MessageConstant.QUERY_QUESTION_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.QUERY_QUESTION_FAIL);
        }


    }
    private Result delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            //1. 获取请求参数并封装
            String[] ids = BeanUtil.fillBeanFromJson(request, String[].class);
            //2.调用service层方法,编辑数据
            questionService.delete(ids);
            //3.响应结果
            return new Result(true,MessageConstant.DELETE_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_QUESTION_FAIL);
        }

    }

    private Result edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        try {
            //1. 获取请求参数并封装
            Question question = BeanUtil.fillBeanFromJson(request, Question.class);
            //2.调用service层方法,编辑数据
            
            questionService.update(question);
            //3.响应结果
            return new Result(true,MessageConstant.EDIT_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_QUESTION_FAIL);
        }


    }

    private Result findById(HttpServletRequest request, HttpServletResponse response) throws IOException {
            
        try {
            //获取请求参数 id
            String id = request.getParameter("id");
            //调用service,根据id查询信息

            Question question = questionService.findById(id);
            //响应给过到客户端
            return new Result(true,MessageConstant.QUERY_QUESTION_SUCCESS,question);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.QUERY_QUESTION_FAIL);
        }


    }

    private Result save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        try {
            //1. 获取请求参数并封装
            Question question = BeanUtil.fillBeanFromJson(request, Question.class);
            //2.调用service层方法,保存数据
            questionService.save(question);
            //3.响应结果
            return new Result(true,MessageConstant.SAVE_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SAVE_QUESTION_FAIL);
        }

    }

    private Result findByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            //1.获取请求参数 currentPage和pageSize
            String currentPageSrt = request.getParameter("currentPage");
            String pageSizeSrt = request.getParameter("pageSize");
            //2.非空校验并赋默认值
            int currentPage=1,pageSize=5;
            if (!StringUtils.isBlank(currentPageSrt)){
                 currentPage = Integer.parseInt(currentPageSrt);
            }
            if (!StringUtils.isBlank(pageSizeSrt)){
                pageSize = Integer.parseInt(pageSizeSrt);
            }
            //3.调用service层方法,执行查询pageInfo
            PageInfo<Question> info = questionService.findByPage(currentPage, pageSize);
            //4.响应结果
            return new Result(true, MessageConstant.QUERY_QUESTION_SUCCESS,info);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }
}
